import pandas as pd
import json
import plotly.express as px

bilidf = pd.read_json('src/data/bilidata.json')
bilidf['date']= pd.to_datetime(bilidf['pubdate'], unit='s')
bilidf['dateDay']= bilidf['date'].dt.date
dataPlay= bilidf[['date','play','favorites']].sort_values(by='date', ascending=False).iloc[:1100].groupby(bilidf['dateDay']).sum()
biliplayfig = px.line(
    x=dataPlay.index, y=dataPlay.play, # replace with your own data source
    title="B站《天道》二创视频播放量",labels=dict(x="日期", y="播放量")
)
bililikefig= px.line(
    x=dataPlay.index, y=dataPlay.favorites, # replace with your own data source
    title="B站《天道》二创视频收藏数",labels=dict(x="日期", y="播放量")
)
movieComments = pd.read_json('src/data/MoviewComments.json')
## 每天的评论数
movieComments['date']= pd.to_datetime(movieComments['date'], unit='s')
movieComments['dateDay']= movieComments['date'].dt.date
dataComment= movieComments[['date','comment']].sort_values(by='date', ascending=False).iloc[:1100].groupby(movieComments['dateDay']).count()
doubanReviewNumfig=px.line(x=dataComment.index, y=dataComment.comment, # replace with your own data source
    title="豆瓣《天道》影评每日评论数", labels=dict(x="日期", y="评论数"))

import plotly.express as px
from wordcloud import WordCloud
words = ''.join([i for i in bilidf.title.to_list()])
## 去除数字，特殊符号
import re
words = re.sub(r'\d+', '', words)
## 去除英文
words = re.sub(r'[a-zA-Z]+', '', words)
## 去除高频词
words = words.replace('天道', '').replace('王志文','').replace('台','')
wordcloud=WordCloud(background_color='white',margin=2,font_path='src/static/font/SourceHanSerif-VF.ttf.ttc').generate(words)
BiliWordfig = px.imshow(wordcloud,width=600,labels=dict(x="", y=""),title="B站《天道》二创视频标题词云图").update_xaxes(showticklabels = False).update_yaxes(showticklabels = False)

words = ''.join([i for i in movieComments.comment.to_list()])
wordcloud=WordCloud(background_color='white',margin=2,font_path='src/static/font/SourceHanSerif-VF.ttf.ttc').generate(words)
doubanWordfig=px.imshow(wordcloud,width=600,labels=dict(x="", y=""),title="豆瓣《天道》影评词云图").update_xaxes(showticklabels = False).update_yaxes(showticklabels = False)



dataxiaohongshu = json.load(open('src/data/xiaohongshu_trend.json', 'r', encoding='utf-8'))
datacount = [item['list'][0]['totalCount'] for item in dataxiaohongshu['data']]
date = [item['date'] for item in dataxiaohongshu['data']]

xiaohongshudataframe = pd.DataFrame({'date': date, 'count': datacount})
xiaohongshudataframe['date'] = pd.to_datetime(xiaohongshudataframe['date'])
xiaohongshudataframe['count'] = xiaohongshudataframe['count'].astype('int')
xiaohongshudataframe = xiaohongshudataframe.set_index('date')

xiaohongshuplayfig = px.line(x=xiaohongshudataframe.index, y=xiaohongshudataframe['count'],title="小红书《天道》每日点赞数", width=400,labels=dict(x="日期", y="点赞"))# replace with your own data source


Vdata = json.load(open('src/data/xinVday.json', 'r', encoding='utf-8'))
datas = {}
for key in ["totalComment", "totalForward", "totalLike", "videoCount",'time']:
    datas[key] = [item[key] for item in Vdata[0]['days']]

dataframe = pd.DataFrame(datas)
dataframe['time'] = pd.to_datetime(dataframe['time'])
for key in ["totalComment", "totalForward", "totalLike", "videoCount"]:
    dataframe[key] = dataframe[key].astype('int')
dataframe = dataframe.set_index('time')

xinVfigs = {}
namemap = {
    "totalComment": "评论数",
    "totalForward": "转发数",
    "totalLike": "点赞数",
    "videoCount": "视频数"
}
for key in ["totalComment", "totalForward", "totalLike", "videoCount"]:
    xinVfigs[key] = px.line(x=dataframe.index, y=dataframe[key],title=f"视频号《天道》每日{namemap[key]}",labels=dict(x="日期", y=namemap[key]))


data = json.load(open('src/data/baiduIndexPeople.json', 'r', encoding='utf-8'))
## 饼图表示男女比例
genderpie = px.pie(values=[data['result'][0]['gender'][1]['rate'],data['result'][0]['gender'][0]['rate']],names=['男','女'],title='《天道》搜索人群性别比例',hole=0.5,width=400,height=400)
## 饼图表示年龄比例
agepie = px.pie(values=[data['result'][0]['age'][0]['rate'],data['result'][0]['age'][1]['rate'],data['result'][0]['age'][2]['rate'],data['result'][0]['age'][3]['rate'],data['result'][0]['age'][4]['rate']],names=['19岁以下','20-29岁','30-39岁','40-49岁','50岁以上'],title='《天道》搜索人群年龄比例',hole=0.5,width=400,height=400)


areadata = json.load(open('src/data/baiduIndexRegion.json', 'r', encoding='utf-8'))
from .map import provinces
dataRegion= pd.DataFrame({'location':list(areadata['prov'].keys()) , '近期热度': list(areadata['prov'].values())})
dataRegion['location'] = dataRegion['location'].apply(lambda x: provinces[x])

with open("src/data/china_province.geojson", encoding='utf8') as f:
    provinces_map = json.load(f)
areamap = px.choropleth_mapbox(
    data_frame=dataRegion,
    geojson=provinces_map,
    color='近期热度',
    locations="location",
    featureidkey="properties.NL_NAME_1",
    mapbox_style="white-bg",
    color_continuous_scale='viridis',
    center={"lat": 37.110573, "lon": 106.493924},
    zoom=2,
    width=600,
    height=600,
    opacity=0.5,
    title='《天道》搜索人群地域分布'
)